<style scoped>
.fixed {
    position: fixed;
    top: 0;
}
</style>

<script setup>

defineProps({
    zIndex: {
        type: Number,
        default: 1
    }
})
import { onMounted } from 'vue';
const isFixed = ref(false);
const initTopValue = ref(0);
const initWidth = ref(0)
const refDom = ref(null)
const checkScrollPosition = () => {
    if (window.scrollY > initTopValue.value) {
        isFixed.value = true;
    } else {
        isFixed.value = false;
    }
};

onMounted(() => {
    setTimeout(() => {
        // initTopValue.value = refDom.value.getBoundingClientRect().top;
        const { top, width } = refDom.value.getBoundingClientRect()
        initTopValue.value = top;
        // initWidth.value = width; 
        refDom.value.style.width = `${width}px`;

    }, 300);
    window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
});

const handleScroll = () => {
    let timer = null;
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(() => {
        checkScrollPosition();
    }, 100);
}
</script>
<template>
    <div ref="refDom" :class="{ 'fixed': isFixed }" :style="{ top: initTopValue, zIndex: zIndex }">
        <slot>

        </slot>
    </div>
</template>